import errorMapping from './errors.js'
import axios from "axios";
import {ElMessage} from 'element-plus'

const BASE_URL = import.meta.env.VITE_APP_BASE_URL;  //使用参数获取请求接口地址
axios.defaults.baseURL = BASE_URL
axios.defaults.timeout = 5000

/**
 * Ajax请求拦截
 */
axios.interceptors.request.use(
    (config) => {
        return config;
    },
    (err) => {
        ElMessage.error({
            message: "请求超时",
            duration: 3000
        });
        return Promise.reject(err);
    }
)

/**
 * Ajax响应拦截
 */
axios.interceptors.response.use(
    //正常
    (response) => {
        let serverData = response.data//response.data是后端返回的json数据
        if (!serverData.success) {
            ElMessage.error({
                message: serverData.message,
                duration: 3000
            });
        }
        return serverData;
    },
    //异常
    (error) => {
        console.log(error)
        let errorMessage
        //如果服务器端返回了错误信息
        if (error.response.data && error.response.data.message) {
            errorMessage = error.response.data.message
        } else { //根据http status 提示错误信息
            let status = error.response.status + '';
            errorMessage = errorMapping[status] ? errorMapping[status] : errorMapping.DEFAULT
        }
        ElMessage.error({
            message: errorMessage,
            duration: 3000
        });
        return Promise.reject(error.response)   // 返回接口返回的错误信息
    }
)

export default axios